package com.ojoin.ojoin.eb_spider.service.impl;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.jms.Destination;

import org.apache.http.HttpResponse;
import org.openqa.selenium.Cookie;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.ojoin.ojoin.eb_spider.service.CookieService;
import com.ojoin.ojoin.eb_spider.service.HttpResponseService;
import com.ojoin.ojoin.eb_spider.utils.WebServiceUtils;
import com.ojoin.trade.common.utils.CacheUtils;
import com.ojoin.trade.common.utils.CommonUtils;
import com.ojoin.trade.common.utils.LogUtils;
import com.ojoin.trade.common.utils.URLUtils;
import com.ojoin.trade.common.utils.json.JSONUtils;
import com.ojoin.trade.supplyloan_core.constdef.IPlatformUrlDef;
import com.ojoin.trade.supplyloan_core.web.domain.JedisObject;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;

@Service("cookieServiceDB")
public class CookieServiceImplDB implements CookieService {

	@Autowired
	private HttpResponseService httpResponseService;

	/*@Autowired
	private QueueSenderServieImpl queueSenderServie;
	*/
	/*@Autowired
	@Qualifier("catchDateMessage")
	private Destination destination;*/
	
	private static Logger log = LoggerFactory.getLogger(CookieServiceImplDB.class);
	
	/**
	 * 记录 uid cookie 保持登陆是失败的次数
	 * 
	 */
	//private Map<Integer,Integer> map = new HashMap<Integer,Integer>();}

	@Override
	public boolean saveCookies(String uid, Set<Cookie> cookie) {
		JedisObject ob = new JedisObject();
		ob.setCacheName(CacheUtils.COOKIE);
		ob.setKey(uid);
		ob.setValue(JSONUtils.toJSONString(cookie));
		 
		//queueSenderServie.send(destination, ob);
		return false;
	}

	@Override
	public Set<Cookie> getCookies(String uid) throws Exception {
		Set<Cookie> set = new HashSet<Cookie>();
		
		JedisObject dict = WebServiceUtils.queryJedisObject(CacheUtils.COOKIE, uid);
		if(!CommonUtils.isEmpty(dict)){
			Set cookies = JSONUtils.parseObject(dict.getValue(), Set.class);
			
			if (!CommonUtils.isEmpty(cookies)) {
				Iterator it = cookies.iterator();
				while (it.hasNext()) {
					Map map = (Map) it.next();
					String name = (String)(map.get("name"));
					String value =  (String)(map.get("value"));
					String domain = (String)(map.get("domain"));		
					String path = (String)(map.get("path"));
					String expiry = (String)(map.get("expiry"));
					boolean secure = (boolean)(map.get("secure"));
					boolean httpOnly = (boolean)(map.get("httpOnly"));
					
					Cookie co = new Cookie(name, value, domain, path, null, secure, httpOnly);
							//Cookie co = new Cookie((String)(, (String)(map.get("path")), (String)(map.get("expiry")), (String)(map.get("secure")), (String)(map.get("httpOnly")));
					
					set.add(co);

				}
			}
		}
		
		return set;
	}

	@Override
	public void cookieKeeyOnline(List<TbSlPlatformUser> list) {
		
		if(!CommonUtils.isEmpty(list)){
			for(TbSlPlatformUser user:list){
				/*Integer failure = map.get(user.getId());
				if(!CommonUtils.isEmpty(failure) && failure > 2 ){
					LogUtils.info(log, " Uid[%s] name[%s] cookie failure count [%s] skip",user.getId(),user.getUsername(),failure);
				}*/
				
				List<String> li = IPlatformUrlDef.mapUrl.get(user.getPlatformName());

				if(CommonUtils.isEmpty(li)){
					LogUtils.error(log, "no init url to keep online");
					return ;
				}
				int key = (int) (Math.random() * li.size());

				String logedurl = li.get(key);
				
				try {
					StringBuffer sb = new StringBuffer();
					
					Set<Cookie> set =  getCookies(user.getId()+"");
					
					if(!CommonUtils.isEmpty(set)){
						for(Cookie cookie:set){
							sb.append(cookie.getName()+"="+cookie.getValue()+";");
						}
					}
					
					HttpResponse httpResponse = URLUtils.isLoginByUrl(sb.toString(), logedurl);
					
					if(httpResponseService.isLogin(httpResponse)){
						LogUtils.info(log, " Uid[%s] name[%s] cookie keep success  ",user.getId(),user.getUsername());
					}else {
						LogUtils.info(log, " Uid[%s] name[%s] cookie keep failure  ",user.getId(),user.getUsername());
					
					}
				} catch (Exception e) {
					LogUtils.error(log, "get cookie error"+ user.getId());
					return ;
				}
				
			}
		}
		
		
		
		//WebServiceUtils.getPlatformUserList(joinid)
	}
	
}
